<template>
	<view class="login-container">
		<view class="login-content">
			<!-- Logo区域 -->
			<view class="logo-section">
				<view class="logo-icon">
					<text class="logo-emoji">🧠</text>
				</view>
				<text class="logo-title">智能宇宙</text>
				<text class="logo-subtitle">连接宇宙，经营生命，创造价值</text>
			</view>

			<!-- 登录卡片 -->
			<view class="login-card">
				<!-- 登录/注册切换 -->
				<view class="auth-toggle">
					<view 
						@click="setIsLogin(true)" 
						:class="['toggle-btn', { active: isLogin }]"
						:style="{ opacity: isLoading ? 0.6 : 1 }"
					>
						登录
					</view>
					<view 
						@click="setIsLogin(false)" 
						:class="['toggle-btn', { active: !isLogin }]"
						:style="{ opacity: isLoading ? 0.6 : 1 }"
					>
						注册
					</view>
				</view>

				<!-- 表单 -->
				<view class="form-container">
					<!-- 手机号输入 -->
					<view class="input-group">
						<text class="input-label">手机号</text>
						<view class="input-wrapper">
							<uni-icons type="phone" size="20" color="#666" class="input-icon"></uni-icons>
							<input 
								class="input-field"
								type="number"
								placeholder="请输入手机号"
								v-model="formData.phone"
								@input="handleInputChange('phone', $event.detail.value)"
								maxlength="11"
							/>
						</view>
					</view>

					<!-- 密码输入 -->
					<view v-if="loginMode === 'password'" class="input-group">
						<text class="input-label">密码</text>
						<view class="input-wrapper">
							<uni-icons type="locked" size="20" color="#666" class="input-icon"></uni-icons>
							<input 
								class="input-field"
								type="text"
								placeholder="请输入密码"
								:value="showPassword ? formData.password : getPasswordDisplay()"
								@input="handlePasswordInput"
							/>
							<view 
								class="password-toggle"
								@click="togglePassword"
							>
								<uni-icons 
									:type="showPassword ? 'eye' : 'eye-slash'" 
									size="20" 
									color="#666"
									class="toggle-icon"
								></uni-icons>
							</view>
						</view>
					</view>

					<!-- 验证码输入 -->
					<view v-if="loginMode === 'verify'" class="input-group">
						<text class="input-label">验证码</text>
						<view class="input-wrapper" style="display: flex; align-items: center;">
							<uni-icons type="locked" size="20" color="#666" class="input-icon"></uni-icons>
							<input 
								class="input-field"
								type="text"
								placeholder="请输入验证码"
								v-model="formData.verifyCode"
								@input="handleInputChange('verifyCode', $event.detail.value)"
								style="flex:1;"
								maxlength="6"
							/>
							<button 
								class="send-code-btn"
								:disabled="smsLoading || countdown > 0 || !formData.phone || !/^1\d{10}$/.test(formData.phone)"
								@click="sendSmsVerifycode"
								style="margin-left: 16rpx; min-width: 140rpx; height: 56rpx; font-size: 22rpx; border-radius: 12rpx; background: #3b82f6; color: #fff;"
							>
								{{ smsLoading ? '发送中...' : (countdown > 0 ? countdown + 's' : '发送验证码') }}
							</button>
						</view>
					</view>

					<!-- 注册时的额外字段 -->
					<view v-if="!isLogin" class="register-fields">
						<view class="input-group">
							<text class="input-label">确认密码</text>
							<view class="input-wrapper">
								<uni-icons type="locked" size="24" color="#666" class="input-icon"></uni-icons>
								<input 
									class="input-field"
									type="password"
									placeholder="请再次输入密码"
									v-model="formData.confirmPassword"
									@input="handleInputChange('confirmPassword', $event.detail.value)"
								/>
							</view>
						</view>
						<view class="input-group">
							<text class="input-label">验证码</text>
							<view class="input-wrapper" style="display: flex; align-items: center;">
								<input 
									class="input-field"
									type="text"
									placeholder="请输入验证码"
									v-model="formData.verifyCode"
									@input="handleInputChange('verifyCode', $event.detail.value)"
									style="flex:1;"
									maxlength="6"
								/>
								<button 
									class="send-code-btn"
									:disabled="smsLoading || countdown > 0 || !formData.phone || !/^1\d{10}$/.test(formData.phone)"
									@click="sendSmsVerifycode"
									style="margin-left: 16rpx; min-width: 140rpx; height: 56rpx; font-size: 22rpx; border-radius: 12rpx; background: #3b82f6; color: #fff;"
								>
									{{ smsLoading ? '发送中...' : (countdown > 0 ? countdown + 's' : '发送验证码') }}
								</button>
							</view>
						</view>
					</view>

					<!-- 忘记密码链接 -->
					<view v-if="isLogin && loginMode === 'password'" class="forgot-password">
						<view class="forgot-link">忘记密码？</view>
					</view>

					<!-- 提交按钮 -->
					<button 
						class="submit-btn"
						:class="{ loading: isLoading }"
						:disabled="isLoading"
						@click="handleSubmit"
					>
						<view v-if="isLoading" class="loading-spinner"></view>
						<text class="submit-text">{{ isLoading ? (isLogin ? '登录中...' : '注册中...') : (isLogin ? (loginMode === 'password' ? '登录' : '验证码登录') : '注册') }}</text>
						<text class="arrow-icon">→</text>
					</button>
				</view>

				<!-- 社交登录 -->
				<view class="social-login">
					<view class="divider">
						<text class="divider-text">或</text>
					</view>
					
					<view class="social-buttons">
						<view 
							class="social-btn wechat-btn"
							@click="handleSocialLogin('wechat')"
							:style="{ opacity: isLoading ? 0.6 : 1 }"
						>
							<uni-icons type="chat" size="20" color="#07c160" class="social-icon"></uni-icons>
							<text class="social-text">微信登录</text>
						</view>
						
						<view class="social-row">
							<view 
								class="social-btn verify-btn"
								@click="switchToVerifyLogin"
								:style="{ opacity: isLoading ? 0.6 : 1 }"
							>
								<text class="social-text">{{ loginMode === 'password' ? '验证码登录' : '密码登录' }}</text>
							</view>
							
							<view 
								class="social-btn google-btn"
								@click="handleSocialLogin('google')"
								:style="{ opacity: isLoading ? 0.6 : 1 }"
							>
								<text class="social-text">Google</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 切换登录模式 -->
				<view class="switch-mode">
					<view class="switch-content">
						<text class="switch-text">
							{{ isLogin ? '还没有账号？' : '已有账号？' }}
						</text>
						<view 
							class="switch-link"
							@click="setIsLogin(!isLogin)"
							:style="{ opacity: isLoading ? 0.6 : 1 }"
						>
							{{ isLogin ? '立即注册' : '立即登录' }}
						</view>
					</view>
				</view>
			</view>

			<!-- 服务条款 -->
			<view class="terms">
				<text class="terms-text">
					继续使用即表示您同意我们的
					<text class="terms-link">服务条款</text>
					和
					<text class="terms-link">隐私政策</text>
				</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isLogin: true,
				showPassword: false,
				isLoading: false,
				smsLoading: false,
				countdown: 0, // 新增倒计时
				timer: null,  // 新增定时器
				error: null,
				loginMode: 'password', // 登录模式：password 或 verify
				formData: {
					phone: '',
					password: '',
					confirmPassword: '',
					verifyCode: '' // 新增验证码字段
				}
			}
		},
		onLoad() {
			console.log('Login页面加载')
		},
		methods: {
			csfn() {
				// 点击Logo的处理函数
				this.$message.success('Logo被点击了！')
				const token = uni.getStorageSync('token')
				console.log(token)
			},
			setIsLogin(value) {
				this.isLogin = value
				this.error = null
			},
			
			switchToVerifyLogin() {
				// 切换登录模式
				this.loginMode = this.loginMode === 'password' ? 'verify' : 'password'
				this.error = null
				// 清空相关字段
				if (this.loginMode === 'password') {
					this.formData.verifyCode = ''
				} else {
					this.formData.password = ''
				}
			},
			
			handleInputChange(field, value) {
				this.formData[field] = value
				if (this.error) {
					this.error = null
				}
			},
			
			togglePassword() {
				this.showPassword = !this.showPassword
			},
			
			getPasswordDisplay() {
				return this.formData.password ? '*'.repeat(this.formData.password.length) : ''
			},
			
			handlePasswordInput(event) {
				const value = event.detail.value
				if (this.showPassword) {
					// 显示模式下，直接更新密码
					this.formData.password = value
				} else {
					// 隐藏模式下，需要处理星号输入
					const currentLength = this.formData.password.length
					const newLength = value.length
					
					if (newLength > currentLength) {
						// 添加字符
						const addedChar = value.slice(currentLength)
						this.formData.password += addedChar
					} else if (newLength < currentLength) {
						// 删除字符
						this.formData.password = this.formData.password.slice(0, newLength)
					}
				}
				
				if (this.error) {
					this.error = null
				}
			},
			
			validateForm() {
				if (!this.formData.phone) {
					return '请输入手机号'
				}
				if (!/^1\d{10}$/.test(this.formData.phone)) {
					return '请输入正确的手机号'
				}
				
				if (this.isLogin) {
					// 登录验证
					if (this.loginMode === 'password') {
						if (!this.formData.password) {
							return '请输入密码'
						}
					} else if (this.loginMode === 'verify') {
						if (!this.formData.verifyCode) {
							return '请输入验证码'
						}
					}
				} else {
					// 注册验证
					if (!this.formData.password) {
						return '请输入密码'
					}
					if (!this.formData.confirmPassword) {
						return '请再次输入密码'
					}
					if (this.formData.password !== this.formData.confirmPassword) {
						return '两次输入的密码不一致'
					}
					if (!this.formData.verifyCode) {
						return '请输入验证码'
					}
				}
				return null
			},
			
			async handleSubmit() {
				this.isLoading = true
				this.error = null
				
				try {
					const validationError = this.validateForm()
					if (validationError) {
						throw new Error(validationError)
					}
					
					if (this.isLogin) {
						// 登录逻辑
						if (this.loginMode === 'verify') {
							// 验证码登录
							await this.verifyCodeLogin()
						} else {
							// 密码登录
							await this.passwordLogin()
						}
					} else {
						// 注册逻辑
						await this.register()
					}
					
				} catch (error) {
					console.error('Auth error:', error)
					this.error = error.message || (this.isLogin ? '登录失败' : '注册失败')
					// 显示错误消息
					this.$message.error(this.error)
				} finally {
					this.isLoading = false
				}
			},
			
			// 验证码登录
			async verifyCodeLogin() {
				try {
					const { verifyCodeLogin } = await import('@/api/auth.js')
					const response = await verifyCodeLogin({
						phone: this.formData.phone,
						code: this.formData.verifyCode,
						login_type: 'smsLogin'
					})
					
					// 处理登录成功
					this.handleLoginSuccess(response)
					
				} catch (error) {
					throw new Error('验证码登录失败：' + (error.message || '未知错误'))
				}
			},
			
			// 密码登录
			async passwordLogin() {
				// 模拟密码登录
				await new Promise(resolve => setTimeout(resolve, 2000))
				
				const mockAuthData = {
					id: 'user_' + Date.now(),
					phone: this.formData.phone,
					name: '用户',
					token: 'mock_token_' + Date.now(),
					userType: 'personal'
				}
				
				this.handleLoginSuccess(mockAuthData)
			},
			
			// 注册
			async register() {
				// 模拟注册
				await new Promise(resolve => setTimeout(resolve, 2000))
				
				const mockAuthData = {
					id: 'user_' + Date.now(),
					phone: this.formData.phone,
					name: '用户',
					token: 'mock_token_' + Date.now(),
					userType: 'personal'
				}
				
				this.handleLoginSuccess(mockAuthData)
			},
			
			// 处理登录成功
			async handleLoginSuccess(authData) {

				try {
					// 1. 先存储token
					uni.setStorageSync('token', authData.token)
					
					// 2. 获取用户信息
					const { getUserInfo } = await import('@/api/auth.js')
					const userInfo = await getUserInfo()
					
					// 3. 存储用户信息
					uni.setStorageSync('userInfo', JSON.stringify(userInfo))
					
					// 显示成功消息
					this.$message.success(this.isLogin ? '登录成功！' : '注册成功！')
					
					// // 跳转到首页
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}, 1500)
					
				} catch (error) {
					console.error('获取用户信息失败:', error)
					// 即使获取用户信息失败，也继续跳转（因为token已经存储）
					this.$message.success(this.isLogin ? '登录成功！' : '注册成功！')
					
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}, 1500)
				}
			},
			
			async handleSocialLogin(provider) {
				this.isLoading = true
				this.error = null
				
				try {
					// 模拟社交登录
					await new Promise(resolve => setTimeout(resolve, 1500))
					
					const mockAuthData = {
						id: 'user_' + Date.now(),
						phone: `${provider}_user@example.com`,
						name: `${provider}用户`,
						token: `mock_${provider}_token_${Date.now()}`,
						userType: 'personal',
						provider: provider
					}
					
					// 存储到本地
					uni.setStorageSync('mock-session', JSON.stringify(mockAuthData))
					
					// 显示成功消息
					this.$message.success(`${provider} 登录成功！`)
					
					// 跳转到首页
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}, 1500)
					
				} catch (error) {
					console.error('Social login error:', error)
					this.error = `${provider} 登录失败: ${error.message}`
					// 显示错误消息
					this.$message.error(this.error)
				} finally {
					this.isLoading = false
				}
			},
			
			// 发送短信验证码
			async sendSmsVerifycode() {
				if (this.smsLoading || this.countdown > 0) return
				this.smsLoading = true
				try {
					const { sendSmsVerifycode } = await import('@/api/auth.js')
					await sendSmsVerifycode(this.formData.phone)
					this.$message.success('短信验证码发送成功')
					// 启动倒计时
					this.countdown = 99
					this.timer = setInterval(() => {
						if (this.countdown > 0) {
							this.countdown--
						} else {
							clearInterval(this.timer)
							this.timer = null
						}
					}, 1000)
				} catch (error) {
					this.$message.error('短信验证码发送失败')
				} finally {
					this.smsLoading = false
				}
			}
		},
		onUnload() {
			// 页面卸载时清理定时器
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-container {
		min-height: 100vh;
		background: linear-gradient(to bottom right, #f8fafc, #eff6ff, #faf5ff);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40rpx;
		position: relative;
		overflow: hidden;
	}

	.login-content {
		width: 100%;
		position: relative;
		z-index: 10;
		animation: scaleIn 0.6s ease-out;
	}

	.logo-section {
		text-align: center;
		margin-bottom: 80rpx;
		
		.logo-icon {
			display: inline-flex;
			align-items: center;
			justify-content: center;
			width: 120rpx;
			height: 120rpx;
			background: linear-gradient(135deg, #8b5cf6, #3b82f6);
			border-radius: 24rpx;
			margin-bottom: 40rpx;
			box-shadow: 0 8rpx 24rpx rgba(139, 92, 246, 0.2);
			
			.logo-emoji {
				font-size: 56rpx;
			}
		}
		
		.logo-title {
			font-size: 44rpx;
			font-weight: 700;
			background: linear-gradient(135deg, #8b5cf6, #3b82f6);
			-webkit-background-clip: text;
			background-clip: text;
			color: transparent;
			margin-bottom: 16rpx;
			display: block;
		}
		
		.logo-subtitle {
			font-size: 26rpx;
			color: #6b7280;
			display: block;
			line-height: 1.5;
		}
	}

	.login-card {
		background: #0000004d;
		border-radius: 36rpx;
		padding: 48rpx 40rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		position: relative;
		z-index: 10;
	}

	.auth-toggle {
		display: flex;
		background: #f3f4f6;
		border-radius: 24rpx;
		padding: 6rpx;
		margin-bottom: 40rpx;
		
		.toggle-btn {
			flex: 1;
			line-height: 0.8;
			padding: 20rpx 24rpx;
			border-radius: 20rpx;
			font-size: 26rpx;
			transition: all 0.2s ease;
			background: transparent;
			border: none;
			display: flex;
			align-items: center;
			justify-content: center;
			text-align: center;
			
			&.active {
				background: #ffffff;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
				color: #111827;
			}
			
			&:not(.active) {
				color: #6b7280;
			}
			
			&:disabled {
				opacity: 0.6;
			}
		}
	}

	.form-container {
		display: flex;
		flex-direction: column;
		gap: 32rpx;
		margin-bottom: 32rpx;
	}

	.input-group {
		display: flex;
		flex-direction: column;
		gap: 4rpx;
		margin-bottom: 8rpx;
		
		.input-label {
			font-size: 26rpx;
			font-weight: 500;
			color: #374151;
		}
	}

	.input-wrapper {
		position: relative;
		display: flex;
		align-items: center;
		
		.input-icon {
			position: absolute;
			left: 20rpx;
			z-index: 1;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.input-field {
			width: 100%;
			height: 60rpx;
			padding: 0 20rpx 0 80rpx;
			border: 1rpx solid #6b728080;
			border-radius: 18rpx;
			font-size: 26rpx;
			background: rgb(162,166,173);
			transition: all 0.2s ease;
			box-sizing: border-box;
			
			&:focus {
				border-color: #8b5cf6;
				box-shadow: 0 0 0 4rpx rgba(139, 92, 246, 0.1);
			}
		}
		
		.password-toggle {
			position: absolute;
			right: 20rpx;
			background: none;
			border: none;
			padding: 8rpx;
			
			.toggle-icon {
				font-size: 28rpx;
				color: #9ca3af;
			}
		}
	}

	.register-fields {
		display: flex;
		flex-direction: column;
		gap: 32rpx;
	}

	.forgot-password {
		display: flex;
		justify-content: flex-end;
		margin-bottom: 0;
		
		.forgot-link {
			font-size: 24rpx;
			color: #3b82f6;
			padding: 8rpx 0;
			text-align: right;
			
			&:active {
				color: #1d4ed8;
			}
		}
	}

	.submit-btn {
		width: 100%;
		height: 60rpx;
		background: linear-gradient(135deg, #8b5cf6, #3b82f6);
		border: none;
		border-radius: 18rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
		transition: all 0.2s ease;
		margin-bottom: 32rpx;
		
		&:active {
			background: linear-gradient(135deg, #7c3aed, #2563eb);
			transform: translateY(1rpx);
		}
		
		&.loading {
			opacity: 0.8;
		}
		
		&:disabled {
			opacity: 0.6;
		}
		
		.loading-spinner {
			width: 28rpx;
			height: 28rpx;
			border: 3rpx solid rgba(255, 255, 255, 0.3);
			border-top: 3rpx solid #ffffff;
			border-radius: 50%;
			animation: spin 1s linear infinite;
		}
		
		.submit-text {
			font-size: 24rpx;
			font-weight: 500;
			color: #ffffff;
		}
		
		.arrow-icon {
			font-size: 28rpx;
			color: #ffffff;
		}
	}

	.social-login {
		margin-top: 32rpx;
		
		.divider {
			display: flex;
			align-items: center;
			margin-bottom: 24rpx;
			
			&::before,
			&::after {
				content: '';
				flex: 1;
				height: 0.3rpx;
				background: #6b7280;
			}
			
			.divider-text {
				padding: 0 20rpx;
				font-size: 22rpx;
				color: #6b7280;
			}
		}
		
		.social-buttons {
			display: flex;
			flex-direction: column;
			gap: 12rpx;
			
			.social-btn {
				width: 100%;
				height: 60rpx;
				border: 1rpx solid #e5e7eb;
				border-radius: 18rpx;
				background: #ffffff;
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 12rpx;
				transition: all 0.2s ease;
				text-align: center;
				
				&:active {
					background: #f9fafb;
					transform: translateY(1rpx);
				}
				
				&:disabled {
					opacity: 0.6;
				}
				
				&.wechat-btn {
					.social-text {
						color: #07c160;
					}
				}
				
				&.verify-btn {
					.social-text {
						color: #3b82f6;
					}
				}
				
				&.google-btn {
					.social-text {
						color: #4285f4;
					}
				}
				
				.social-icon {
					font-size: 28rpx;
				}
				
				.social-text {
					font-size: 24rpx;
					font-weight: 500;
				}
			}
			
			.social-row {
				display: flex;
				gap: 12rpx;
				
				.social-btn {
					flex: 1;
				}
			}
		}
	}

	.switch-mode {
		text-align: center;
		margin-top: 32rpx;
		
		.switch-content {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 8rpx;
		}
		
		.switch-text {
			font-size: 22rpx;
			color: #6b7280;
		}
		
		.switch-link {
			font-size: 22rpx;
			color: #3b82f6;
			padding: 4rpx 0;
			
			&:active {
				color: #1d4ed8;
			}
		}
	}

	.terms {
		text-align: center;
		margin-top: 40rpx;
		
		.terms-text {
			font-size: 20rpx;
			color: #6b7280;
			line-height: 1.5;
		}
		
		.terms-link {
			color: #3b82f6;
			
			&:active {
				color: #1d4ed8;
			}
		}
	}

	/* 动画 */
	@keyframes scaleIn {
		from { 
			transform: scale(0.95);
			opacity: 0;
		}
		to { 
			transform: scale(1);
			opacity: 1;
		}
	}

	@keyframes spin {
		from { transform: rotate(0deg); }
		to { transform: rotate(360deg); }
	}
</style>